function MinePublishJobController(analyseId){
	
	this.jobDialog = null;
	this.flowsParam = {};
	
	/**
	 * 运行任务
	 */
	var runJob = function(job){
		$.ajax({
			url : contextPath + '/api/ai/mine/publish/runJob',
			type : 'post',
			data : {id : job.id, triggerId : job.jobId},
			success : function(obj) {
				if (obj) {
					console.log(obj);
				}
			}
		});
	}
	/**
	 * 停止任务
	 */
	var stopJob = function(job){
		$.ajax({
			url : contextPath + '/api/ai/mine/publish/stopJob',
			type : 'post',
			data : {id : job.id, triggerId : job.jobId},
			success : function(obj) {
				if (obj) {
					console.log(obj);
				}
			}
		});
	}
	
	var deleteJob = function(job){
		var jobId = job.jobId;
		$("<div/>").confirm({
			title :  TempoUtils.locale("mine.publish-btn-delete"), 
			msg :  TempoUtils.locale("mine.publish-mine-job-grid-col-delete-confirm"),
			height : 120,
			width : "auto",
			ok : function(){
				$.ajax({
					url : contextPath + '/api/ai/mine/publish/deleteJob',
					type : 'post',
					data : {triggerId : jobId, id : job.id},
					success : function(obj) {
						$('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
					}
				});
			}
		});
	}
	
	var editJob = function(job){
		var that = this;
		newJob.apply(that, [job,true]);
	}
	
	/**
	 * 新增调度
	 */
	var newJob = function(job, isEdit){
		var that = this;
		that.jobDialog = $('#tempo-mine-flow-job-dialog').clone().appendTo('body');
		that.jobDialog.dialog({
			width : 680,
			minHeight: 500,
			autoOpen : false,
			title: TempoUtils.locale('mine.publish-mine-job-dialog-title'),
			modal:true,
			resizable: false,
			close:function(){
				that.jobDialog.dialog("destroy");
			},
			buttons:[{
				text: TempoUtils.locale('mine.publish-dialog-sure'),
				click:function(){
					saveJobConfig.apply(that, [job, isEdit]);
				}
			},{
				text:TempoUtils.locale('mine.publish-dialog-cancel'),
				click:function(){
					that.jobDialog.dialog("destroy");
				}
			}]
		});
		
		that.jobDialog.dialog('open');
		initJobLayout.apply(that, isEdit ? [job] : null);
	}
	
	/**
	 * 初始化表单数据
	 */
	var initFormData = function(job){
		var that = this;
		var dialog = that.jobDialog;
		//调度名称
		if(job){
			dialog.find('input[name="id"]').val(job.id);
			dialog.find('input[name="name"]').val(job['trigger.name']);
			dialog.find('select[name="triggertype"]').val(job['trigger.triggertype']);
			dialog.find('input[name="starttime"]').val(job['trigger.starttime']);
			dialog.find('input[name="endtime"]').val(job['trigger.endtime']);
			dialog.find('select[name="priority"]').val(job['trigger.priority']);
		}
		dialog.find('input[name="name"]').validatebox({validator: true, required: true});
		dialog.find('input[name="starttime"]').validatebox({validator: true, required: true});
	}
	
	
	/**
	 * 保存调度信息
	 */
	var saveJobConfig = function(oldjob, isEdit){
		var that = this;
		if(!validateForm(this.jobDialog)){
			return;
		}
		//暂存流程参数
		saveFlowParam.apply(that);
		
		var job = {
				themeId : analyseId,
				trigger : {
				},
				publishFlowIds : []
		}
		if(isEdit){
			job.id = oldjob.id;
			job.jobId = oldjob.jobId;
			job.creator = oldjob.creator;
			job.trigger.id = oldjob.jobId;
		}
		//调度参数
		var triggerParam = {};
		var trigger = job.trigger;
		var publishFlowIds = [];
		//调度信息
		var jobconfig = that.jobDialog.find('#tempo-mine-flow-config').serializeArray();
		$.each(jobconfig, function(index, item){
			if(!item.name.startsWith('flow_')){
				trigger[item.name] = item.value;
			}
		});
		//由于之前的界面改动，此处的优先级信息需要手动获取，wtf
		var priority =  that.jobDialog.find('select[name="priority"]').val();
		trigger.priority = priority;
		
		
		//引用流程信息
		var relatedFlows = that.jobDialog.find('#selectFlowTable').find('tr');
		var relatedFlow = [];
		relatedFlows.each(function(i){
			 var flows = $(this).find('select').serializeArray();
			 var rflowObj = {};
			 $.each( flows, function(index, item){
				if($.inArray(item.value, publishFlowIds) == -1){
					if(item.value){
						publishFlowIds.push(item.value);
					}
				}
				if(item.value){
					rflowObj[item.name] = item.value;
				}
			 });
			 if(!$.isEmptyObject(rflowObj)){
				 relatedFlow.push(rflowObj);
			 }
		});
		
		triggerParam.flowsInJob = relatedFlow;
		
		if(publishFlowIds.length > 0){
			if(publishFlowIds.length == 1){
				job.publishFlowIds = publishFlowIds[0];
			}else{
				job.publishFlowIds = publishFlowIds.join(',');
			}
		}
		
		//流程配置参数
		triggerParam.flowsParam = that.flowsParam;
		job.trigger.param = JSON.stringify(triggerParam);
		var url = isEdit ? contextPath + '/api/ai/mine/publish/editJob' : contextPath + '/api/ai/mine/publish/saveJob';
		$.ajax({
			url : url,
			type : 'post',
			data : JSON.stringify(job),
			contentType : 'application/json',
			success : function(obj) {
				if (obj) {
					that.jobDialog.dialog("destroy");
					$('#mine-opt-job-grid').jqGrid().trigger("reloadGrid");
				}
			}
		});
	}
	
	/**
	 * 暂存流程参数
	 */
	var saveFlowParam = function(){
		var that = this;
		var paramsTable = that.jobDialog.find('#tempo-mine-flow-param table');
		var currentFlow = paramsTable.attr('flowId');
		if(currentFlow){
			var currentFlowParams = that.flowsParam[currentFlow] || []
			var paramsLine = paramsTable.find('tr');
			paramsLine.each(function(i){
				var params = $(this).find('input').serializeArray();
				var param = {};
				$.each(params, function(index, item){
					if(item.value){
						param[item.name] = item.value;
					}
				});
				if(!$.isEmptyObject(param)){
					currentFlowParams.push(param);
				}
			});
			that.flowsParam[currentFlow] = currentFlowParams;
		}
	}
	
	/**
	 * 新增调度对话框
	 */
	var initJobLayout = function(job){
		var that = this;
		var dialog = that.jobDialog;
		dialog.find('#tempo-mine-flow-job').height(340).layout({
			north : {
				resizable : false,
				size : 120,
				spacing_open : 1,
				closable : false
			},center : {
				
			}
		});
		
		dialog.find('.datetimefield').datetimepicker({showSecond: true, timeFormat : 'HH:mm:ss'});
		initFormData.apply(that, [job]);
		initSelectFlowTable.apply(that, job? [job] : null);
	}
	
	/**
	 * 新增流程选择
	 */
	var addNewFlowRow = function(target, data){
		var that = this;
		var dialog = that.jobDialog;
		var allFlows = dialog.find('#selectFlowTable tbody tr');
		var fids = [];
		//上级流程待选
		var fEles = [];
		allFlows.each(function(i){
			var fele = $(this).find('td:first select')
			var fid = fele.val();
			if(fids.indexOf(fid) == -1){
				fids.push(fid);
				fEles.push(fele.find('option[value="' + fid + '"]').clone());
			}
		});
		
		//本级流程
		var addContent = $(target).parents('tr.firstSeletedFlow').clone();
		var tds = addContent.find('td');
		var firstFlows = tds.first().find('select option');
		if(firstFlows.length == fids.length){
			return;
		}
		var firstFlowEles = []
		firstFlows.each(function(i){
			var fid = $(this).attr('value');
			if(fids.indexOf(fid) == -1){
				firstFlowEles.push($(this).clone());
			}
		});
		tds.first().find('select').empty().append(firstFlowEles);
		
		tds.last().empty();
		var deleteFlowRow = $('<span>').addClass('job-flow-deletebtn ui-icon ui-icon-minus').text(TempoUtils.locale('mine.publish-btn-delete')).bind('click',removeRow);
		tds.last().append(deleteFlowRow);
		tds.eq(1).find('select').empty().append(fEles);
		dialog.find('#selectFlowTable').append(addContent);
		if(data){
			addContent.find('select:first').val(data.flow_current);
			addContent.find('select').eq(1).val(data.flow_parent);
		}
	}
	
	
	
	var initSelectFlowTable = function(job){
		var that = this;
		var dialog = that.jobDialog;
		var flows = $('#mine-published-grid').jqGrid('getRowData');
		//待编辑数据
		var flowParams = null;
		if(job){
			flowParams = JSON.parse(job['trigger.param']);
		}
		//初始化流程选择下拉框
		var html = '';
		var flowTableTr = dialog.find('#flowTableTr');
		var paramTableTr = dialog.find('#paramTableTr');
		if(flows && flows.length > 0){
			flowTableTr.show();
			for (var i = 0; i < flows.length; i++) {
				var flow = flows[i];
				var name = flow.name;
				var id = flow.id;
				if(i == 0){
					dialog.find('#setFlowParamTable').attr('flowId', id);
				}
				html += '<option value="' + id + '">' + name + '</option>';
			}
		}else{
			flowTableTr.empty().hide();
			paramTableTr.empty().hide();
		}
		
		dialog.find('.flow-select').each(function(){
			$(this).html(html);
		});
		
		dialog.find('.flow-select').bind('change', function(){
			flowSelectHandler.apply(that,[this])
		});
		
		if(flowParams){
			var selectedFlows = flowParams.flowsInJob;
			var flowParam = flowParams.flowsParam;
			that.flowsParam = flowParams.flowsParam;
			if(selectedFlows && selectedFlows.length > 0){
				for (var i = 0; i < selectedFlows.length; i++) {
					if(i==0){
						dialog.find('.flow-select:first').val(selectedFlows[i].flow_current);
						flowSelectHandler.apply(that,[dialog.find('.flow-select:first')]);
					}else{
						addNewFlowRow.apply(that,[dialog.find('#selectFlowTable .job-flow-addbtn'), selectedFlows[i]])
					}
				}
			}
		}
		
		
		if(flows && flows.length > 1){
			dialog.find('#selectFlowTable .job-flow-addbtn').show();
			//新增一行flow选择
			dialog.find('#selectFlowTable .job-flow-addbtn').unbind('click').bind('click', function(){
				addNewFlowRow.apply(that,[this])
			});
		}else{
			//如果只有一个流程则隐藏新增按钮
			dialog.find('#selectFlowTable .job-flow-addbtn').hide();
		}
	}
	
	/**
	 * 流程选择事件处理
	 */
	var flowSelectHandler = function(target, dialog){
		var that = this;
		var dialog = that.jobDialog;
		//先保存之前的流程参数配置
		saveFlowParam.apply(that);
		var flowid = $(target).val();
		var params = that.flowsParam[flowid];
		dialog.find('#setFlowParamTable').attr('flowId', $(target).val());
		if(params && params.length > 0){
			for (var int = 0; int < params.length; int++) {
				var p = params[i];
//				dialog.find('#setFlowParamTable tr').get(i).find('')
			}
		}else{
			dialog.find('#setFlowParamTable tr input').val('');
		}
		
	}
	
	/**
	 * 删除表格一行
	 */
	var removeRow = function(){
		$(this).parent('td').parent('tr').remove();
	}
	
	
	/**
	 * 调度列表事件
	 */
	var bindJobGridEvent = function(){
		var that = this;
		var grid = $('#mine-opt-job-grid');

		grid.find(".edit-job-btn").unbind("click").bind("click",function(e){
			e.stopPropagation();
			var rowid = $(e.target).attr('rowid');
			var row = grid.jqGrid("getRowData", rowid);
			editJob.apply(that, [row]);
		});
		grid.find(".run-job-btn").unbind("click").bind("click",function(e){
			debugger;
			e.stopPropagation();
			var rowid = $(e.target).attr('rowid');
			var row = grid.jqGrid("getRowData", rowid);
			runJob(row);
		});
		grid.find(".stop-job-btn").unbind("click").bind("click",function(e){
			e.stopPropagation();
			var rowid = $(e.target).attr('rowid');
			var row = grid.jqGrid("getRowData", rowid);
			stopJob(row);
		});
		grid.find(".del-job-btn").unbind("click").bind("click",function(e){
			e.stopPropagation();
			var rowid = $(e.target).attr('rowid');
			var row = grid.jqGrid("getRowData", rowid);
			deleteJob(row);
		});
		
		grid.find(".log-job-btn").unbind("click").bind("click",function(e){
			e.stopPropagation();
			var rowid = $(e.target).attr('rowid');
			var log = $(e.target).attr('logid');
			var runResult = $(e.target).attr('runResult');
			var row = grid.jqGrid("getRowData", rowid);
			downloadLog(row.id, log, runResult);
		});
		grid.find(".viewlog").each(function(){
			var rowid = $(this).attr('rowid');
			var row = null;
			var rows = grid.data('rows');
			if(rows && rows.length > 0){
				for (var m = 0; m < rows.length; m++) {
					if(rowid == rows[m].id){
						row = rows[m];
					}
				}
			}
			var logs = row.logs;
			var content;
			if(logs && logs.length > 0){
				var logele = $('<ul>').css({
					'list-style-type' : 'none'
				});
				for (var i = 0; i < logs.length; i++) {
					var log = logs[i];
					var date = new Date(Number.parseFloat(log.runTime));
					var logName = DateUtils.formatDateTime(date, 'yyyy-MM-dd HH:mm:ss')
					var liele = $('<li class="logitem">').attr('jobid', rowid).attr('logid', log.runTime).attr('runResult', log.runResult).attr('name', logName);
					var liicon = $("<span>").addClass("ui-icon ui-icon-document").appendTo(liele);
					var lilabel = $("<label>").text(logName).appendTo(liele);
					logele.append(liele);
				}
				content = $('<div>').append(logele).html();
			}
			$(this).webuiPopover({
				trigger : 'hover',
				title : '',
				cache : false,
				placement : 'right',
				width : 180,		
				closeable : false,
				arrow : true,
				content : content
			})
			$(this).on('shown.webui.popover', function(){
				$('.logitem').each(function(index, domEle){
					$(domEle).off('click').on('click',function(){
						var jobid = $(this).attr('jobid');
						var logid = $(this).attr('logid');
						var runResult = $(this).attr('runResult');
						var name = $(this).attr('name');
						downloadLog(jobid, logid, name, runResult);
					})
				});
			});
		});
	}
	
	/**
	 * 下载任务日志
	 */
	var downloadLog = function(id, log, name,runResult){
		debugger;
		TempoUtils.downLoadFile({
			url: contextPath + "/api/ai/mine/publish/downloadJobLog",
			data : {
				id : id,
				name : name,
				log : log,
				runResult : runResult
			}
		});
	}
	/**
	 * 初始化调度列表
	 */
	this.initJobGrid = function() {
		var that = this;
		var height = $('#publish-mine-config').height()-155;
		var width = $('#publish-mine-config').width()-30;
		that.grid = $('#mine-opt-job-grid').jqGrid({
			datatype : "json",
			url : contextPath + '/api/ai/mine/publish/listJob?time=' + new Date().getTime(),
			postData : {themeId : analyseId},
			height : height,
			width : width,
			rownumbers : true,
			mtype : 'POST',
			autowidth:true,
			rownumbers : true,
			shrinkToFit : true, 
			viewrecords : true,
			loadui:'disable',
			colNames : [ 'id', 
			             'jobId',
			             'triggertype',
			             'priority',
			             'starttime',
			             'endtime',
			             'param',
			             'logs',
			             TempoUtils.locale("mine.publish-mine-job-grid-col-name"),//'任务名称'
			             TempoUtils.locale("mine.publish-mine-job-grid-col-priority"),//'优先级'
			             TempoUtils.locale("mine.publish-mine-job-grid-col-creator"),//'创建者'
			             TempoUtils.locale("mine.publish-mine-job-grid-col-lasttime"),//'上次执行时间'
			             TempoUtils.locale("mine.publish-mine-job-grid-col-lastcosttime"),//'上一次执行耗时'
			             TempoUtils.locale("mine.publish-mine-job-grid-col-nexttime"),//'下一次执行时间'
			             TempoUtils.locale("mine.publish-mine-job-grid-col-relatedflow"),//'涉及流程'
			             TempoUtils.locale("mine.publish-mine-job-grid-col-log"),//'日志'
			             TempoUtils.locale("mine.publish-mine-job-grid-col-status"),//'状态'
			             TempoUtils.locale("mine.publish-mine-job-grid-col-opt")],//'操作'
			colModel : [{
						name : 'id',
						index : 'id',
						hidden : true
					},{
						name : 'jobId',
						index : 'jobId',
						hidden : true
					},{
						name : 'trigger.triggertype',
						index : 'trigger.triggertype',
						hidden : true
					},{
						name : 'trigger.priority',
						index : 'trigger.priority',
						hidden : true
					},{
						name : 'trigger.starttime',
						index : 'trigger.starttime',
						hidden : true
					},{
						name : 'trigger.endtime',
						index : 'trigger.endtime',
						hidden : true
					},{
						name : 'trigger.param',
						index : 'trigger.param',
						hidden : true
					},{
						name : 'logs',
						index : 'logs',
						hidden : true
					},{
						name : 'trigger.name',
						index : 'trigger.name',
						resizable:false,
						sortable : false
					},{
						name : '',
						index : '',
						align : 'center',
						width : 50,
						sortable:false,
						formatter : function(val, grid, rows, state) {
							var obj = rows.trigger.priority;
							if(obj == '1'){
								return  TempoUtils.locale("mine.publish-mine-job-priority-high");
							}else if(obj == '2'){
								return  TempoUtils.locale("mine.publish-mine-job-priority-middle");
							}else if(obj == '3'){
								return  TempoUtils.locale("mine.publish-mine-job-priority-low");
							}
							return "";
						}
					},{
						name : 'creator',
						index : 'creator',
						width : 80,
						sortable:false
					},{
						name : 'trigger.prevtime',
						index : 'trigger.prevtime',
						resizable:false,
						sortable : false
					},{
						name : 'cost',
						index : 'cost',
						width : 85,
						resizable:false,
						sortable : false,
						formatter : function(obj, grid, rows, state) {
							if(rows.cost > 0){
								return rows.cost + TempoUtils.locale("mine.publish-mine-job-exe-second");
							}
							return "";
						}
					},{
						name : 'trigger.nexttime',
						index : 'trigger.nexttime',
						resizable:false,
						sortable : false
					},{
						name : 'publishFlowIds',
						index : 'publishFlowIds',
						resizable:false,
						sortable : false,
						width : 100,
						formatter : function(obj, grid, rows, state) {
							var flows = $('#mine-published-grid').jqGrid('getRowData');
							var html = [];
							if(flows && flows.length > 0){
								for (var i = 0; i < flows.length; i++) {
									var flow = flows[i];
									var id = flow.id;
									if(obj.indexOf(id) > -1){
										html.push(flow.name);
									}
								}
							}
							return html.join(';') 
						}
					},{
						name : '',
						index : '',
						sortable : false,
						align : 'left',
						width : 40,
						formatter : function(obj, grid, rows, state) {
							var logs = rows.logs;
							var logHtml = [];
							return "<a href='javascript:;void(0)' rowid='" + rows.id + "' class='viewlog'>"+TempoUtils.locale("mine.publish-mine-job-log-view")+"</a>";
						}
					},{
						name : 'trigger.status',
						index : 'trigger.status',
						sortable : false,
						width : 120, 
						formatter : function(obj, grid, rows, state) {
							var success = rows.successCount || 0;
							var fail = rows.failedCount || 0;
							return  TempoUtils.locale("mine.publish-mine-job-exe-success") +"<span style='color:green'>" + success + "</span>" +TempoUtils.locale("mine.publish-mine-job-exe-time")+ "　" + TempoUtils.locale("mine.publish-mine-job-exe-fail") + "<span style='color:red'>" + fail + "</span>" +TempoUtils.locale("mine.publish-mine-job-exe-time");
						}
					},{
						name : '',
						index : '',
						sortable : false,
						width : 100,
						align : 'left',
						fixed : false,
						formatter : function(obj, grid, rows, state) {
							var edit = $("<a>").attr("href", "javascript:;void(0)").append($("<span>").attr("rowid", rows.id).addClass("ui-icon ui-icon-wrench")).attr("title", TempoUtils.locale("mine.publish-btn-edit")).addClass('ui-corner-all gridoptbtn edit-job-btn');
//							var run = $("<a>").attr("href", "javascript:;void(0)").append($("<span>").attr("rowid", rows.id).addClass("ui-icon ui-icon-play")).attr("title", "运行").addClass('ui-corner-all gridoptbtn run-job-btn');
							var stop = $("<a>").attr("href", "javascript:;void(0)").append($("<span>").attr("rowid", rows.id).addClass("ui-icon ui-icon-stop")).attr("title", TempoUtils.locale("mine.publish-btn-stop")).addClass('ui-corner-all gridoptbtn stop-job-btn');
							var del = $("<a>").attr("href", "javascript:;void(0)").append($("<span>").attr("rowid", rows.id).addClass("ui-icon ui-icon-minus")).attr("title", TempoUtils.locale("mine.publish-btn-delete")).addClass('ui-corner-all gridoptbtn del-job-btn');
							return edit.prop("outerHTML") + "&nbsp;" + stop.prop("outerHTML") + "&nbsp;" + del.prop("outerHTML");
						}
					}],
			gridComplete : function(rowid,row) {
			},
			loadComplete : function(datas){
				var rows = datas.rows;
				$(this).data('rows', rows);
				bindJobGridEvent.apply(that);
			},
			rowNum : 20,
			rowList : [ 10, 20, 30 ],
			pager : $('#mine-opt-job-grid-pager')
		});
	}
	
	/**
	 * 校验表单
	 */
	var validateForm = function(dialog){
//		dialog.find('input[name="name"]').val(job['trigger.name']);
//		dialog.find('input[name="starttime"]').val(job['trigger.starttime']);
		return dialog.find('form').formValidate();
	}
		
	
	
	this.initOrrefresh = function(){
		var that = this;
		if(!this.grid){
			this.initJobGrid();
			$('#jobsearcher').searchbar({
				onSearch : function(text){
					var name = text.trim();
					if(name && name.length > 0){
						that.grid.jqGrid('setGridParam',
								{
									postData : {
										name : name
									}
								}).trigger("reloadGrid");
					}else{
						that.grid.jqGrid('setGridParam',
								{
									postData : {themeId : analyseId, name : null}
								}).trigger("reloadGrid");
					}
				}
			});
			$('#mine-opt-job-newbtn').button().click($.proxy(newJob, that));
		}else{
			that.grid.jqGrid('setGridParam',
					{
						postData : {themeId : analyseId, name : null}
					}).trigger("reloadGrid");
		}
	}
	
}